//Third Person Status : Handles player state machine
using UnityEngine;
using System.Collections;

public class ThirdPersonStatus : MonoBehaviour
{
	public int health = 10;
	public int maxHealth = 10;
	public int lives = 4;
	
	//Sound Effects
	public AudioClip struckSound;
	public AudioClip deathSound;
	
	//Link to script that handles level complete sequence
	private LevelStatus levelStateMachine;
	
	//Total items to pickup on this level
	private int remainingItems;
	
	void Awake()
	{
		levelStateMachine = (LevelStatus)FindObjectOfType(typeof(LevelStatus));
		if(!levelStateMachine)
		{
			Debug.Log("No link to Level Status");
		}	
		remainingItems = levelStateMachine.itemsNeeded;
	}
	
	//Utility function used by the HUD script
	public int GetRemainingItems()
	{
		return remainingItems;
	}
	
	public void ApplyDamage(int damage)
	{
		if(struckSound)
		{
			//Play the player struck sound
			AudioSource.PlayClipAtPoint(struckSound, transform.position);
		}
		
		//Update player health
		health -=damage;
		if(health <= 0)
		{
			SendMessage("Die");
		}	
	}
	
	public void AddLife(int powerUp)
	{
		lives += powerUp;
		health = maxHealth;
	}
	
	public void AddHealth(int powerUp)
	{
		health += powerUp;
		if(health>maxHealth)
		{
			health = maxHealth;
		}
	}
	
	public void FoundItem(int numFound)
	{
		remainingItems -= numFound;
		
		if(remainingItems == 0)
		{
			levelStateMachine.UnlockLevelExit();	
		}
	}
	
	public void FalloutDeath()
	{
		Die();
		return;
	}
	
	public IEnumerator Die()
	{
		//Play death sound if available
		if(deathSound)
		{
			AudioSource.PlayClipAtPoint(deathSound, transform.position);
		}
		
		lives--;
		health = maxHealth;
		
		if(lives < 0)
		{
			Application.LoadLevel("GameOver");
		}	
		
		//If the player still has lives here, respawn
		Vector3 respawnPosition = Respawn.currentRespawn.transform.position;
		//Reset camera
		Camera.main.transform.position = respawnPosition - (transform.forward * 4) + Vector3.up;
		//Hide the player to finish death sequence
		//Hide player also disables controls
		SendMessage("HidePlayer");
		
		//Relocate the player. or the camera will still focus on death area
		transform.position = respawnPosition + Vector3.up;
		
		//Allow death sound to complete
		yield return new WaitForSeconds(1.6f);
		
		//Show player, then initiate particle effect
		SendMessage("ShowPlayer");
		Respawn.currentRespawn.FireEffect();
	}
	
	public void LevelCompleted()
	{
		levelStateMachine.LevelCompleted();	
	}
}

